package org.pine.security02.service;

import org.pine.security02.mapper.UserMapper;
import org.pine.security02.model.Role;
import org.pine.security02.model.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * @ClassName UserService
 * @Description 用户接口服务
 * @Author liucs
 * @Date 2021-02-18
 * @Version V1.0
 */
@Service
public class UserService implements UserDetailsService {

    @Resource
    UserMapper userMapper;

    /**
     *
     * @param username 用户名
     * @return userDetails实例
     * @throws UsernameNotFoundException 用户名未找到异常
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.loadUserByUsername(username);
        System.out.println("get user:"+user);
        if (user==null){
            throw new UsernameNotFoundException("账号不存在");
        }
        user.setRoles(userMapper.getUserRolesByUid(user.getId()));
        // 得到用户拥有的角色
        List<Role> roles=user.getRoles();
        for (Role role:roles) {
            System.out.println("role:"+ role);

        }
        //得到授权
        Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
        for (GrantedAuthority auth:authorities) {
            System.out.println("auth:"+auth.getAuthority());
        }

        return user;
    }
}
